package com.shiwaixiangcun.customer.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import butterknife.ButterKnife
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterSurround
import com.shiwaixiangcun.customer.adapter.MerchTypeAdapter
import com.shiwaixiangcun.customer.app.App.getContext
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.AllMerchBean
import com.shiwaixiangcun.customer.entity.SurroundMerchantTypeBean
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.Utils
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import com.shiwaixiangcun.customer.widget.RoundImageView
import kotlinx.android.synthetic.main.activity_surround_life.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @author Administrator
 */
class SurroundLifeActivity : BaseActivity(), View.OnClickListener {

    private var mGvMerchType: RecyclerView? = null
    private var mSurroundHeader: View? = null
    private var mAdapterSurround: AdapterSurround? = null
    private val mSurroundHeaderList = ArrayList<SurroundMerchantTypeBean.DataBean>()
    private val mSurroundContentList = ArrayList<AllMerchBean.DataBean.ElementsBean>()
    private var merchTypeAdapter: MerchTypeAdapter? = null
    private var allId: String? = null
    private var mTvFirstItemName: TextView? = null
    private var mTvFirstItemFeature: TextView? = null
    private var mIvFirstItemCover: RoundImageView? = null
    private var llayoutTitle: LinearLayout? = null
    private var mTvListTitle: TextView? = null
    private var mIvTitleL: ImageView? = null
    private var mIvTitleR: ImageView? = null
    private var firstItem: AllMerchBean.DataBean.ElementsBean? = null
    private var mCurrentPage: Int = 0
    private var mPageSize: Int = 0

    private var mSiteId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_surround_life)
        ButterKnife.bind(this)
        EventUtil.getInstance().register(this)
        initViewAndEvent()
        initData()
    }

    /**
     * 初始化视图
     */
    private fun initViewAndEvent() {
        mSiteId = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int
        mCurrentPage = GlobalConfig.first_page
        mPageSize = GlobalConfig.page_size
        mAdapterSurround = AdapterSurround(mSurroundContentList)
        merchTypeAdapter = MerchTypeAdapter(mSurroundHeaderList)
        //初始化Header视图
        mSurroundHeader = LayoutInflater.from(mContext).inflate(R.layout.head_surround, null)
        mGvMerchType = mSurroundHeader?.findViewById(R.id.mgv_merch_type)
        mTvFirstItemName = mSurroundHeader?.findViewById(R.id.tv_first_name_merch)
        mTvFirstItemFeature = mSurroundHeader?.findViewById(R.id.tv_first_feature)
        mIvFirstItemCover = mSurroundHeader?.findViewById(R.id.iv_first_merch)
        llayoutTitle = mSurroundHeader!!.findViewById(R.id.ll_merch_wonderful)
        mTvListTitle = mSurroundHeader!!.findViewById(R.id.tv_find_wonderful)
        mIvTitleL = mSurroundHeader!!.findViewById(R.id.iv_find_image_a)
        mIvTitleR = mSurroundHeader!!.findViewById(R.id.iv_find_image_b)
        mAdapterSurround!!.addHeaderView(mSurroundHeader)
        val wm = getContext()
                .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width
        val height = wm.defaultDisplay.height
        //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        val linearParams = mIvFirstItemCover!!.layoutParams as LinearLayout.LayoutParams
        linearParams.width = width - 100
        linearParams.height = (width - 100) / 2
        mIvFirstItemCover!!.layoutParams = linearParams
        tv_page_name!!.text = "周边生活"
        mGvMerchType!!.layoutManager = GridLayoutManager(mContext, 4)
        mGvMerchType!!.adapter = merchTypeAdapter
        rv_recommend!!.layoutManager = LinearLayoutManager(mContext)
        rv_recommend!!.adapter = mAdapterSurround

        val divider = RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setMarginLeft(16f)
                .setMarginRight(16f)
                .setSize(0.5f)
                .setStartSkipCount(1)
                .setEndSkipCount(1)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_recommend.addItemDecoration(divider)
        back_left!!.setOnClickListener(this)


        //contentList  点击回调
        mAdapterSurround!!.setOnItemClickListener { adapter, view, position ->
            val bean = adapter.data[position] as AllMerchBean.DataBean.ElementsBean
            val bundle = Bundle()
            bundle.putString("type", bean.typeValue)
            bundle.putString("merchId", bean.id.toString() + "")
            readyGo(SurroundWebActivity::class.java, bundle)
        }

        merchTypeAdapter!!.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as SurroundMerchantTypeBean.DataBean
            val intent = Intent()
            val bundle = Bundle()
            if (item.detailId != "") {

                bundle.putString("type", item.value)
                bundle.putString("merchId", item.detailId)
                readyGo(SurroundWebActivity::class.java, bundle)

            } else {

                intent.setClass(mContext, SurroundTopActivity::class.java)
                intent.putExtra("merchant", item.id.toString())
                intent.putExtra("nameType", item.name)
                startActivity(intent)


            }

//
        }

        llayoutTitle?.setOnClickListener(this)

        refreshLayout.setOnRefreshListener {
            mCurrentPage = 1
            initTypeData()
            allId?.let { it1 -> initListData(it1, false) }
            mAdapterSurround!!.setEnableLoadMore(false)
        }


        mAdapterSurround!!.setLoadMoreView(CustomLoadMoreView())
        mAdapterSurround!!.setOnLoadMoreListener({
            mCurrentPage += 1
            allId?.let { initListData(it, true) }
        }, rv_recommend)
    }

    private fun initData() {
        initTypeData()

    }

    /**
     * 获取分类
     *
     * @param
     */
    private fun initTypeData() {
        OkGo.get<String>(GlobalApi.merchantType).params("siteId", mSiteId)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        val typeBean = JsonUtil.fromJson(response.body(), SurroundMerchantTypeBean::class.java) ?: return

                        when (typeBean.responseCode) {
                            1001 -> EventUtil.getInstance().post(SimpleEvent(SimpleEvent.SURROUND_LIFE, GET_MERCHANT_TYPE, typeBean))
                            else -> Toast.makeText(mContext, typeBean.message, Toast.LENGTH_LONG).show()
                        }

                    }
                })
    }

    /**
     * 获取List
     *
     * @param
     */
    private fun initListData(id: String?, isLoadMore: Boolean) {

        OkGo.get<String>(GlobalApi.merchant)
                .params("fields", "cover,id,name,feature,typeValue")
                .params("typeId", id)
                .params("siteId", mSiteId)
                .params("page.pn", mCurrentPage)
                .params("page.size", mPageSize)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        Log.e(BUG_TAG, response?.rawCall.toString())
                    }

                    override fun onSuccess(response: Response<String>) {
                        mAdapterSurround?.setEnableLoadMore(true)
                        val responseEntity = JsonUtil.fromJson(response.body(), AllMerchBean::class.java) ?: return
                        when (responseEntity.responseCode) {
                            1001 -> {
                                val size = responseEntity.data.elements.size
                                if (isLoadMore) {
                                    if (size > 0) {
                                        mSurroundContentList.addAll(responseEntity.data.elements)
                                        mAdapterSurround?.notifyDataSetChanged()
                                    }
                                    if (size == 0 || size < mPageSize) {
                                        mAdapterSurround?.loadMoreEnd(false)
                                    } else {
                                        mAdapterSurround?.loadMoreComplete()
                                    }
                                } else {
                                    refreshLayout.finishRefresh()
                                    mAdapterSurround?.setEnableLoadMore(true)
                                    if (size == 0) {
                                    } else {
                                        setContentList(responseEntity)
                                    }
                                }
                            }
                            else -> Log.e(BUG_TAG, "加载失败")
                        }
                    }
                })
    }


    override fun onClick(view: View) {
        val id = view.id
        when (id) {
            R.id.back_left -> finish()
            R.id.ll_merch_wonderful -> if (mSurroundContentList.size != 0) {
                val bundle = Bundle()
                bundle.putString("type", firstItem!!.typeValue)
                bundle.putString("merchId", firstItem!!.id.toString() + "")
                readyGo(SurroundWebActivity::class.java, bundle)
            }
            else -> {
            }
        }
    }

    /**
     * 设置顶部分类数据
     *
     * @param result
     */
    private fun setTypeData(result: SurroundMerchantTypeBean) {

        mSurroundHeaderList.clear()
        val headerList = result.data
        if (headerList.size != 0) {
            for (i in headerList.indices) {
                if (headerList[i].isAll) {
                    allId = headerList[i].id.toString()
                } else {
                    mSurroundHeaderList.add(headerList[i])
                }
            }
            initListData(allId, false)
            merchTypeAdapter!!.notifyDataSetChanged()


        }

    }

    fun setContentList(result: AllMerchBean?) {
        mSurroundContentList.clear()
        mTvListTitle!!.text = "发现精彩"

        mIvTitleL!!.setImageResource(R.mipmap.surround_left)
        mIvTitleR!!.setImageResource(R.mipmap.surround_right)

        if (result!!.data.elements.size > 0) {
            mSurroundContentList.addAll(result.data.elements)

            firstItem = result.data.elements[0]
            mTvFirstItemName!!.text = firstItem!!.name
            mTvFirstItemFeature!!.text = firstItem!!.feature
            if (Utils.isNotEmpty(firstItem!!.cover)) {
                ImageDisplayUtil.showImageView(this, firstItem!!.cover, mIvFirstItemCover)
            }
            mAdapterSurround?.remove(0)
            mAdapterSurround?.notifyDataSetChanged()
        }

        mAdapterSurround?.notifyDataSetChanged()

        if (mSurroundContentList.size == 0) {
            llayoutTitle!!.visibility = View.GONE
        } else {
            llayoutTitle!!.visibility = View.VISIBLE
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent?) {
        if (simpleEvent == null || simpleEvent.mEventType != SimpleEvent.SURROUND_LIFE) {
            return
        }
        when (simpleEvent.mEventValue) {
            GET_MERCHANT_TYPE -> {
                val data = simpleEvent.data as SurroundMerchantTypeBean
                setTypeData(data)
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()

    }

    companion object {

        private val GET_MERCHANT_TYPE = 0x0001
    }
}


